package com.ma.controller;

import com.ma.model.User;
import com.ma.redis.StringRedisServiceImpl;
import com.ma.service.UserService;
import com.ma.utils.MD5Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

/**
 * author: MaHX
 * date: 2019/5/27/16:45
 * description:
 **/
@Controller
public class UserController {
    @Autowired
    UserService userService;

    @Autowired
    StringRedisServiceImpl stringRedisService;

    @ResponseBody
    @PostMapping("/user")
    public User findUserByPhone(@RequestParam("phone") String phone){
        User user = userService.findUserByPhone(phone);
        return user;
    }

    @GetMapping("/register")
    public String register(){
        return "register";
    }

    @PostMapping("/register")
    @ResponseBody
    public String register(User user, HttpServletRequest request){
        String msg = request.getParameter("auth_code");
        String requestUrl = request.getRequestURI().toString();
        String phone = request.getParameter("phone");
        String trueCodeMsg = (String) stringRedisService.get(phone);
        if (trueCodeMsg == null){
            System.out.println("验证码已过期");
        }else if (!trueCodeMsg.equals(msg)){
            System.out.println("验证码错误");
        }else {
            MD5Util md5Util = new MD5Util();
            user.setPassword(md5Util.encode(user.getPassword()));
            int flag = userService.insertUser(user);
            System.out.println("flag:"+flag);

        }
         System.out.println("authcode:"+msg+" url:"+requestUrl);

        return "register";
    }

    @PostMapping("/update")
    @ResponseBody
    public String update(@RequestParam("phone") String phone,@RequestParam("password") String password){
        userService.updatePasswordByPhone(phone,password);
        return "update";
    }
    @PostMapping("/delete")
    @ResponseBody
    public String deleteUser(@RequestParam("phone") String phone){
        userService.deleteUserByPhone(phone);
        return "delete";
    }

    @PostMapping("findUserAndAdress")
    @ResponseBody
    public String findUser(@RequestParam("user_id") String user_id){
        User user = userService.findUserAndAdressByUser_id(user_id);
        return user.toString();
    }

    @PostMapping("findUserAndCar")
    @ResponseBody
    public String findUser(@RequestParam("id") int id){
        User user = userService.findUserAndCarsById(id);
        return user.toString();
    }
}
